package models

import (
	"crypto/md5"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/astaxie/beego/orm"
)

type LoginData struct {
	Id        int64
	User_name string
	Password  string
}

func init() {
	orm.RegisterModel(new(LoginData))
}

//MD5处理
func md5V3(str string) string {
	w := md5.New()
	io.WriteString(w, str)
	md5str := fmt.Sprintf("%x", w.Sum(nil))
	return md5str
}

//第三方登录
func Login(httpType string, url string, username string, password string) (error, interface{}) {
	loginInfo := LoginData{User_name: username, Password: password}
	md5p := md5V3(loginInfo.Password)
	loginInfo.Password = md5p
	jsonInfo, _ := json.Marshal(loginInfo)
	info := string(jsonInfo)
	err, token := Client(httpType, url, info)
	return err, token
}

//*通用接入第三方接口
//*httpType:请求方式（"post","get"）
//*url:请求链接
//*info:请求参数
func Client(httpType string, url string, info string) (error, interface{}) {

	//跳过https证书检测
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	client := &http.Client{Transport: tr}
	request, _ := http.NewRequest(httpType, url, strings.NewReader(info))
	// request, _ := http.NewRequest("POST", "https://192.168.10.198:8099/api/v1/accessor/login", strings.NewReader(string(info)))
	request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	request.Header.Set("Accept-Charset", "utf-8")
	request.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
	request.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
	request.Header.Set("Cache-Control", "max-age=0")
	request.Header.Set("Connection", "keep-alive")

	response, err := client.Do(request)
	errorString := "error"

	//判断接口连接是否报错
	if err != nil {
		fmt.Println(err)
		return err, errorString
	} else {
		if response.StatusCode == 200 {
			body, _ := ioutil.ReadAll(response.Body)
			bodystr := string(body)

			//josn转map
			var mapResult map[string]interface{}
			jsonerr := json.Unmarshal([]byte(bodystr), &mapResult)
			if jsonerr != nil {
				fmt.Println("JsonToMapDemo err: ", jsonerr)
			}
			token := mapResult["data"].(map[string]interface{})["access_token"]
			return err, token
		} else {
			fmt.Println(err)
			return err, errorString
		}
	}
	return err, errorString

}
